package org.geektimes.configuration.microprofile.config.source;

import org.eclipse.microprofile.config.spi.ConfigSource;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * @author :   chuan
 * @date :   2021/03/17
 */
public class ApplicationPropertiesConfigSource implements ConfigSource, ServletContextListener {

    private ServletContext servletContext;

    @Override
    public Set<String> getPropertyNames() {
        Enumeration<String> attributeNames = servletContext.getAttributeNames();
        Set<String> propertyNames = new LinkedHashSet<>();
        while (attributeNames.hasMoreElements()){
            propertyNames.add(attributeNames.nextElement());
        }
        return propertyNames;
    }

    @Override
    public String getValue(String s) {
        return String.valueOf(servletContext.getAttribute(s));
    }

    @Override
    public String getName() {
        return "Application Properties";
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        this.servletContext = sce.getServletContext();
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}
